package app.yj.channel.http;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;


import app.yj.channel.Config;
import app.yj.channel.activity.WebViewActivity;
import app.yj.channel.entity.BlogResult;
import app.yj.channel.event.FinishBrowerEvent;
import app.yj.channel.event.UpdateBrowerUrlEvent;
import app.yj.channel.strategy.PoolStrategy;
import app.yj.channel.ChannelCache;
import app.yj.channel.ChannelManager;
import app.yj.channel.util.EncryptUtil;


/**
 * Anthor:YuYiMing
 * Time:2019/6/27
 */
public class HttpPool {

    /**
     * 开关处理
     *
     * @param link     数据访问地址
     * @param type     类型：国内、国外
     * @param callback 处理回调
     */
    public static void requestTableSwitch(final Context context, final String link, final String type, String name, @NonNull final ChannelManager.ICallback callback, @NonNull final PoolStrategy strategy) {

//        Logger.e("---HttpPool---link:" + link + "\ttype:" + type);

        //        Uri uri = Uri.parse(link);
        //        ViseHttp.POST(uri.getPath())
        //                .baseUrl(uri.getScheme() + "://" + uri.getAuthority())
        ViseHttp.POST(Config.PATH)
                .baseUrl(link)
                .addParam("name", name)
                .addParam("platform", "android") // 平台编码
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(final String data) {
                        if (data != null) {
                            //AES解密
                            String decodeData;
                            try {
                                //解密数据失败
//                                decodeData = EncryptUtil.decrypt(data, Config.pool_key_b1);
                                decodeData = EncryptUtil.decrypt(data, Config.POOL_KEY);
                                final BlogResult blogResult = JSON.parseObject(decodeData, BlogResult.class);
                                if (blogResult != null) {
                                    //请求数据成功
//                                    Logger.e("---HttpPool---link:" + link + "---blogResult:" + blogResult.toString());
                                    onRequestSuccess(context, blogResult, type, callback, strategy);
                                } else {
                                    //解析数据失败
                                    onRequestFail(type, callback, strategy);
                                }
                            } catch (Exception e) {
                                onRequestFail(type, callback, strategy);
                                return;
                            }
                        } else {
                            //请求数据失败
                            onRequestFail(type, callback, strategy);
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        onRequestFail(type, callback, strategy);
                    }
                });
    }


    /**
     * 请求成功
     *
     * @param context
     * @param blogResult
     * @param type
     * @param callback
     */
    private static void onRequestSuccess(final Context context, final BlogResult blogResult, final String type, @NonNull final ChannelManager.ICallback callback, PoolStrategy strategy) {

        strategy.setHttpPool(type, new PoolStrategy.HttpResult(type, true, new PoolStrategy.IResultCallBack() {
            @Override
            public void doCallback() {

//                ChannelCache.setWebUrl("https://www.jd.com/");
//                BusManager.getBus().post(new UpdateBrowerUrlEvent("https://www.jd.com/"));
//                ((Activity) context).finish();

                String newUrl = blogResult.getUrl();
//                Logger.e("---onRequestSuccess---blogResult:"+blogResult.toString());
                //缓存数据
                BlogResult cacheBlogResult = ChannelCache.getBlogResult(context);

                if ((blogResult.getStatus() == 1) && !TextUtils.isEmpty(newUrl)) {
                    //最新结果为开
                    if ((cacheBlogResult != null) && (cacheBlogResult.getStatus() == 1)) {
                        //存在缓存,且缓存结果为开时，对比Url
                        if (!newUrl.equals(cacheBlogResult.getUrl())) {
                            //如果两次不一致,更新Url
                            ChannelCache.setWebUrl(newUrl);
                            BusManager.getBus().post(new UpdateBrowerUrlEvent(newUrl));
                        }
                    } else {
                        //无缓存(或缓存结果为关)，不做对比，直接跳转
                        context.startActivity(WebViewActivity.actionToActivity(context, newUrl, blogResult.getBlackOrWhite(), blogResult.getVersionCol()));
                    }
                    ((Activity) context).finish();
                } else {
                    //最新结果为关
                    if ((cacheBlogResult != null) && (cacheBlogResult.getStatus() == 1)) {
                        //如果缓存已为开,需先关闭后打开
                        ChannelCache.setIsFinishBrowerAndGoApp(true);
                        BusManager.getBus().post(new FinishBrowerEvent());
                    }
                    callback.goApp();
                }
                //缓存最新BlogResult
                ChannelCache.setBlogResult(context, blogResult);
            }
        }));
    }

    /**
     * 请求失败
     *
     * @param type
     * @param callback
     */
    private static void onRequestFail(String type, @NonNull final ChannelManager.ICallback callback, PoolStrategy strategy) {
        strategy.setHttpPool(type, new PoolStrategy.HttpResult(type, false, new PoolStrategy.IResultCallBack() {
            @Override
            public void doCallback() {
                callback.showNetWorkError();
            }
        }));
    }


}